package org.skydiveapp;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import org.skydiveapplibrary.repository.RigRepository;
import org.skydiveapplibrary.ui.GearListSelectAdapter;

import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;

public class GearListSelectActivity extends BaseListActivity
{
	// menus
	private MenuItem addMenu;
	
    @Override 
    public void onCreate(Bundle savedInstanceState)
    { 
    	super.onCreate(savedInstanceState);
    	
		// init view
		getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
		setHeaderText(R.string.gear_list_select_label);
    }
    
    @Override
    public void onResume()
    {
    	super.onResume();
    	
    	loadData();
    }
    
	@Override
    protected void onListItemClick(ListView listView, View view, int indx, long id)
    {
		// update result
		Intent intent =  new Intent();
		intent.putExtra(Constants.EXTRA_SELECTED_RIG_IDS, (Serializable)getSelectedIds());
		setResult(RESULT_OK, intent);
    }
    
    @SuppressWarnings("unchecked")
	private void loadData()
    {
    	// populate list
		RigRepository repository = new RigRepository(this);
		GearListSelectAdapter adapter = new GearListSelectAdapter(
				this,
				repository.getRigs());
		setListAdapter(adapter);
		
		// set initial selection
		List<Integer> selectedIdList = (List<Integer>)getIntent().getSerializableExtra(Constants.EXTRA_SELECTED_RIG_IDS);
		for (int index = 0; index < adapter.getCount(); index++)
		{
			getListView().setItemChecked(index,
					selectedIdList.contains(adapter.getItems().get(index).getId())); 
		}
		
    }
    
    private List<Integer> getSelectedIds()
    {
    	List<Integer> ids = new ArrayList<Integer>();
    	
    	// get adapter
    	GearListSelectAdapter adapter = (GearListSelectAdapter)getListAdapter();
    	// iterate over items
    	for (int index = 0; index < adapter.getItems().size(); index++)
		{
    		if (getListView().getCheckedItemPositions().get(index))
    		{
    			ids.add(adapter.getItems().get(index).getId());
    		}
		}
    	
    	return ids;
    }
    
	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		addMenu = menu.add(R.string.add_button);
		addMenu.setIcon(R.drawable.ic_menu_add);
		
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		if (item == addMenu)
		{
        	Intent intent = new Intent(this, RigEditActivity.class);
        	startActivity(intent);
    		return true;
		}
		else
		{
			return super.onOptionsItemSelected(item);
		}
	}
} 